
const User = require('../model/user')
const { getTime } = require('../util')
const jwt = require('../util/jwt')
require('dotenv').config({ path: `./config/.env.${process.env.NODE_ENV}` })

const jwtSercet = process.env.JWT_SECRET
exports.login = async (req, res, next) => {
  try {
    const user = req.user.toJSON()
    const token = await jwt.sign({
      userId: user._id
    }, jwtSercet, {
      expiresIn: 60 * 60 * 24
    })
    delete user.password
    res.status(200).json({
      ...user,
      token
    })
  } catch (err) {
    next(err)
  }
}
exports.register = async (req, res, next) => {
  try {
    let user = new User(req.body)
    await user.save()
    user = user.toJSON()
    delete user.password
    res.status(201).json({
      user
    })
  } catch (err) {
    next(err)
  }
}
exports.getUser = async (req, res, next) => {
  try {
    const user = await User.findOne({
      username: req.body.username
    })
    if (!user) {
      res.status(404).json({ error: '用户不存在' });
      return
    }
    res.status(200).json({
      user
    })
  } catch (err) {
    next(err)
  }
}